<?php

class WorkflowUtil {
	
	public static function saveWorkflow($flow, $workflowXml) {
		$xmlPath = Yii::app()->runtimePath . "/{$flow['workflow_name']}_{$flow['workflow_version']}.xml";
		if(file_exists($xmlPath)) {
			unlink($xmlPath);
		}
		file_put_contents($xmlPath, $workflowXml);
		try{
			$definition = new ezcWorkflowDefinitionStorageXml(Yii::app()->runtimePath . '/');
			$workflow = $definition->loadByName($flow['workflow_name']);
	
			// Set up database connection.
			$connectionString = StringUtil::getConnectionString(Yii::app()->db->connectionString, 
				Yii::app()->db->driverName, 
				Yii::app()->db->username, 
				Yii::app()->db->password);
			$db = ezcDbFactory::create($connectionString);
	
			// Set up workflow definition storage (database).
			$definition = new ezcWorkflowDatabaseDefinitionStorage( $db );
	
			// Save workflow definition to database.
			$definition->save( $workflow );
			return true;
		}
		catch (Exception $e) {
			Yii::log('save workflow failed: ' . $e->getMessage(), CLogger::LEVEL_ERROR);
			return false;
		}
	}

}